
#include "BlockQueue.hpp"
#include <time.h>
#include <cstdlib>
#include <unistd.h>
#include "Task.hpp"

using namespace my_blockqueue;
using namespace ns_task;

void *consumer(void *args)
{

    BlockQueue<Task> *bq = (BlockQueue<Task> *)args;
    while (true)
    {
        Task t;
        //拿到任务
        bq->Pop(&t);
        //处理任务
        t();
    }
}

void *producter(void *args)
{
    BlockQueue<Task> *bq = (BlockQueue<Task> *)args;
    std::string ops = "+-*/";
    while (true)
    {
        //制造数据
        int x = rand() % 10 + 1; //[1,10];
        int y = rand() % 10 + 1; //[1,10];
        char op = ops[rand() % 4];

        Task t(x, y, op);
        std::cout << "生产者生产一个任务:" << x << op << y << "="
                  << "?" << std::endl;
        //把任务放进生产队列
        bq->Push(t);
        sleep(1);
    }
}

int main()
{
    //随机数生成
    srand((long long)time(nullptr));

    //阻塞队列
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    pthread_t c, p, c1, c2, c3, c4;
    //线程c，p
    //把阻塞队列bq传递过去给线程c，p
    pthread_create(&c, nullptr, consumer, (void *)bq);
    pthread_create(&p, nullptr, producter, (void *)bq);
    pthread_create(&c1, nullptr, producter, (void *)bq);
    pthread_create(&c2, nullptr, producter, (void *)bq);
    pthread_create(&c3, nullptr, producter, (void *)bq);
    pthread_create(&c4, nullptr, producter, (void *)bq);

    pthread_join(c, nullptr);
    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(c3, nullptr);
    pthread_join(c4, nullptr);
    pthread_join(p, nullptr);

    return 0;
}